<template>
    <div>
        <div class="scroll-fixd-sticky-wrap" :style="wrapStyle"></div>
        <div class="scroll-fixed" ref="fixed" :class="{'sticky':isFixed}">
            <slot></slot>
        </div>
    </div>
</template>
<script>

const supportPageOffset = window.pageXOffset !== undefined;
const isCSS1Compat = ((document.compatMode || "") === "CSS1Compat");

export default {
    name:'scroll-fixed',
    data(){
        return {
            top:0,
            isFixed:false,
            wrapStyle:{
                height:0
            }
        }
    },
    mounted(){
        this.top = this.getScrollY();
        window.addEventListener('scroll',this.zScroll)
    },
    destroyed(){
        window.removeEventListener('scroll',this.zScroll)
    },
    methods:{
        getScrollY(){
            return  supportPageOffset ? window.pageYOffset : isCSS1Compat ? document.documentElement.scrollTop : document.body.scrollTop;
        },
        zScroll(e){
            let rect = this.$refs.fixed.getClientRects()[0];
            let y = this.getScrollY();

            // true： pull up false pull domn
            this.$parent.$emit('SCROLL',e,{
                top:y,
                old:this.top,
                flag:y>this.top,
                height:rect.height,
                size:y - this.top
            });
            this.top = y;
            if(rect.top ==0 && y!==0)return false;
            if(y>= rect.top && rect.top !== 0){
                this.isFixed = true;
                this.wrapStyle.height = rect.height + 'px'
            }else{
               this.isFixed = false;
               this.wrapStyle.height = 0
            }
        }
    }
}
</script>
<style lang="less">
.scroll-fixed {
    position: relative;
    z-index:2;
    overflow: hidden;
    &.sticky {
        position:fixed;
        top:0;
        left:0;
        width:100%;
        z-index:999;
    }
}

</style>

